﻿using Microsoft.AspNetCore.Mvc;
using WebHome_API.Models;
using WebHome_API.Models.DataModels;
using WebHome_API.Models.DBModels;
using WebHome_API.Models.OperResult;
using WebHome_API.Tools;

namespace WebHome_API.Controllers
{
    [Route("api/[controller]")]
    [Controller]
    public class GalGameController : ControllerBase
    {

        #region Gal
        [HttpGet("getGalOfTop")]
        public OperResult<List<Gal_Table>> getGalOfTap()
        {
            int minCount = 7;
            List<Gal_Table> ret = new();
            using (var content = new MyContext())
            {
                var list = content.Gals.OrderByDescending(u => u.CreateDate).ToList();
                var cur = list.Where(u => u.CreateDate == list[0].CreateDate).ToList();
                if (cur.Count >= minCount)
                {
                    ret = cur.Take(minCount).ToList();
                }
                else
                {
                    ret = list.Take(minCount).ToList();
                }
                return OperResult<List<Gal_Table>>.Succeed(ret);
            }
        }

        [HttpGet("getGalList")]
        public OperResult<GalList> getGalList(string tagId, string text, int order = 0, int page = 1, int perPage = 20)
        {
            //order[0:不排序 1:按上传时间 2:按名字首字母]
            //包含查询
            GalList data;

            using (MyContext context = new())
            {
                List<Gal_Table> allList = context.Gals.ToList();

                if (order == 1)
                    allList = allList.OrderByDescending(u => u.ID).ToList();
                else if (order == 2)
                    allList = allList.OrderBy(u => u.Name).ToList();

                if (string.IsNullOrEmpty(text) && string.IsNullOrEmpty(tagId))
                {
                    data = new(allList, page, perPage);
                }
                else
                {
                    Dictionary<int, Gal_Table> ret = new();
                    //匹配Tag
                    if (!string.IsNullOrEmpty(tagId))
                    {
                        var arr = tagId.Split(',');

                        List<string> listOfClub = new();
                        List<int> listOfTag = new();
                        foreach (var item in arr)
                        {
                            var galTag = context.FileTags.FirstOrDefault(u => u.ID == Convert.ToInt32(item));
                            if (galTag != null)
                            {
                                if (galTag.TagEnumID == (int)GalTagEnum.club)
                                    listOfClub.Add(galTag.Title);
                                else
                                    listOfTag.Add(galTag.ID);
                            }
                        }

                        //先查社团
                        if (listOfClub.Count != 0)
                        {
                            listOfClub.ForEach(u =>
                            {
                                var temp = allList.Where(p => p.Club == u).ToList();
                                foreach (var item in temp)
                                    ret[item.ID] = item;
                            });
                        }

                        //后查特征
                        //查询拥有这些tag的taglink
                        if (listOfTag.Count != 0)
                        {
                            var tampTagLink = new List<FileTagLink_Table>();
                            //先查TapLink
                            listOfTag.ForEach(u =>
                            {
                                var temp = context.FileTagLink.Where(p => p.TagID == u && p.FileType == FileTypeEnum.Gal).ToList();
                                if (temp.Count != 0)
                                    tampTagLink.AddRange(temp);
                            });
                            //对TagLink查找的Gal进行去重
                            foreach (var item in tampTagLink)
                            {
                                if (!ret.ContainsKey(item.FileID))
                                {
                                    var tempGal = allList.FirstOrDefault(u => u.ID == item.FileID);
                                    if (tempGal != null)
                                        ret[item.FileID] = tempGal;
                                }
                            }
                        }
                    }

                    //最后模糊匹配
                    if (!string.IsNullOrEmpty(text))
                    {
                        var textArr = text.Split(',');

                        foreach (var item in textArr)
                        {
                            var curText = item.Trim().ToLower();
                            allList.Where(u =>
                                u.Name.ToLower().IndexOf(curText) != -1 ||
                                u.NickName.ToLower().IndexOf(curText) != -1 ||
                                u.NewIndex.ToLower().IndexOf(curText) != -1
                            ).ToList().ForEach(u =>
                            {
                                ret[u.ID] = u;
                            });
                        }
                    }
                    data = new GalList(ret.Values.ToList(), page, perPage);
                }

            }

            return OperResult<GalList>.Succeed(data);
        }

        [HttpGet("getGalInfo")]
        public OperResult<GalInfo> getGalInfo(int id = 0)
        {
            using (MyContext context = new())
            {
                var gal = context.Gals.FirstOrDefault(u => u.ID == id && u.IsDel == 0);
                if (gal == null)
                {
                    return OperResult<GalInfo>.Failed($"没有找到[id={id}]的数据");
                }
                var files = context.FilePaths.Where(u => u.FileId == gal.ID && u.FileType == (int)FileTypeEnum.Gal).ToList();
                var url = context.OtherEnums.FirstOrDefault(u => u.ID == 1)!.Text;
                //处理files(这个地方应该交给前端来处理)
                Dictionary<string, List<string>> fileDict = new();
                foreach (var item in files)
                {
                    var name = item.Name.Substring(0, 5);
                    var temp = item.Path.Replace($"\\{name.Substring(0, 1)}\\{name}\\", "");
                    var arr = temp.Split('\\');
                    if (arr.Length >= 2)
                    {
                        if (fileDict.ContainsKey(arr[arr.Length - 2]))
                            fileDict[arr[arr.Length - 2]].Add(url + item.Path.Replace("\\", "/").TrimStart('/'));
                        else
                            fileDict[arr[arr.Length - 2]] = new List<string>() { url + item.Path.Replace("\\", "/").TrimStart('/') };
                    }
                    else
                    {
                        if (fileDict.ContainsKey(name))
                            fileDict[name].Add(url + item.Path.Replace("\\", "/").TrimStart('/'));
                        else
                            fileDict[name] = new List<string>() { url + item.Path.Replace("\\", "/").TrimStart('/') };
                    }
                }
                //处理Tag
                Dictionary<int, FileTag_Table> tagDict = new();
                context.FileTagLink.Where(u => u.FileID == gal.ID && u.FileType == FileTypeEnum.Gal).ToList().ForEach(u =>
                {
                    var tag = context.FileTags.FirstOrDefault(o => o.ID == u.TagID);
                    if (tag != null)
                        tagDict[u.TagID] = tag;
                });

                var galInfo = new GalInfo()
                {
                    ID = gal.ID,
                    Name = gal.Name,
                    NickName = gal.NickName,
                    Club = gal.Club,
                    DownloadCount = gal.DownloadCount,
                    IsCN = gal.IsCN,
                    IsCG = gal.IsCG,
                    Bug = gal.Bug,
                    Url = gal.Url,
                    Files = fileDict,
                    Tags = tagDict.Values.ToList(),
                };
                return OperResult<GalInfo>.Succeed(galInfo);
            }
        }

        [HttpGet("getGalOfNewIndex")]
        public Gal_Table? getGalOfNewIndex(string newIndex)
        {
            using (MyContext content = new())
            {
                return content.Gals.FirstOrDefault(u => u.NewIndex.ToLower() == newIndex.ToLower());
            }
        }
        #endregion


        #region other
        [HttpPost("addGalDownloadCount")]
        public OperResult<int> addGalDownloadCount(int id)
        {
            using (MyContext content = new())
            {
                var data = content.Gals.FirstOrDefault(u => u.ID == Convert.ToInt32(id));
                if (data != null)
                {
                    data.DownloadCount += 1;
                    var ret = content.SaveChanges();
                    return OperResult<int>.Succeed(ret);
                }
                else
                {
                    return OperResult<int>.Failed("当前Gal不存在");
                }
            }
        }

        [HttpGet("getFilePath")]
        public List<string> getFilePath(string fileId)
        {
            List<string> ret = new();
            if (fileId != null)
            {
                using (MyContext context = new())
                {
                    var url = context.OtherEnums.FirstOrDefault(u => u.ID == 1)!.Text;
                    var temp = context.FilePaths.Where(u => u.FileId == Convert.ToInt32(fileId)).ToList();
                    foreach (var item in temp)
                    {
                        ret.Add(url + item.Path.Replace("\\", "/").TrimStart('/'));
                    }
                }
            }
            return ret;
        }
        #endregion


        #region bot
        [HttpGet("getGalInfoOfNewIndex")]
        public OperResult<GalInfo> getGalInfoOfNewIndex(string newIndex)
        {
            if (string.IsNullOrEmpty(newIndex))
            {
                return OperResult<GalInfo>.Failed($"没有找到[{newIndex}]的数据");
            }
            using (MyContext context = new())
            {
                var gal = context.Gals.FirstOrDefault(u => u.NewIndex.ToLower() == newIndex.ToLower() && u.IsDel == 0);
                if (gal == null)
                {
                    return OperResult<GalInfo>.Failed($"没有找到[{newIndex}]的数据");
                }
                var files = context.FilePaths.Where(u => u.FileId == gal.ID && u.FileType == (int)FileTypeEnum.Gal).ToList();
                var url = context.OtherEnums.FirstOrDefault(u => u.ID == 1)!.Text;
                //处理files
                Dictionary<string, List<string>> fileDict = new();
                foreach (var item in files)
                {
                    var name = item.Name.Substring(0, 5);
                    var temp = item.Path.Replace($"\\GalGame\\{name.Substring(0, 1)}\\{name}\\", "");
                    var arr = temp.Split('\\');
                    if (arr.Length >= 2)
                    {
                        if (fileDict.ContainsKey(arr[arr.Length - 2]))
                            fileDict[arr[arr.Length - 2]].Add(url + item.Path.Replace("\\", "/").TrimStart('/'));
                        else
                            fileDict[arr[arr.Length - 2]] = new List<string>() { url + item.Path.Replace("\\", "/").TrimStart('/') };
                    }
                    else
                    {
                        if (fileDict.ContainsKey("default"))
                            fileDict["default"].Add(url + item.Path.Replace("\\", "/").TrimStart('/'));
                        else
                            fileDict["default"] = new List<string>() { url + item.Path.Replace("\\", "/").TrimStart('/') };
                    }
                }


                var galInfo = new GalInfo()
                {
                    ID = gal.ID,
                    Name = gal.Name,
                    NickName = gal.NickName,
                    NewIndex = gal.NewIndex,
                    Club = gal.Club,
                    DownloadCount = gal.DownloadCount,
                    IsCN = gal.IsCN,
                    IsCG = gal.IsCG,
                    Bug = gal.Bug,
                    Url = gal.Url,
                    Files = fileDict
                };
                return OperResult<GalInfo>.Succeed(galInfo);
            }
        }

        [HttpGet("getGalOfIndexof")]
        public OperResult<GalInfoList> getGalOfIndexof(string text, int page = 1)
        {
            if (string.IsNullOrEmpty(text))
            {
                return OperResult<GalInfoList>.Failed($"请指定通配符数据");
            }
            int curCount = 20;
            int curPage = 1;
            if (page <= 0)
                curPage = 1;
            else
                curPage = page;
            using (MyContext context = new())
            {
                var list = context.Gals
                     .Where(u => u.IsDel == 0)
                     .Where(u =>
                         u.Name.ToLower().IndexOf(text) != -1 ||
                         u.NickName.ToLower().IndexOf(text) != -1)
                     .ToList();

                List<GalInfo> ret = new();
                foreach (var item in list.Skip((curPage - 1) * curCount).Take(curCount))
                {
                    ret.Add(new GalInfo()
                    {
                        Name = item.Name,
                        NickName = item.NickName,
                        NewIndex = item.NewIndex,
                        IsCN = item.IsCN,
                    });
                }
                int curMaxCount = list.Count;
                int curMaxPage = curMaxCount % curCount == 0 ? curMaxCount / curCount : curMaxCount % curCount + 1;
                return OperResult<GalInfoList>.Succeed(new GalInfoList()
                {
                    GalInfos = ret,
                    Count = curCount,
                    MaxCount = curMaxCount,
                    Page = curPage,
                    MaxPage = curMaxPage,
                });
            }
        }

        [HttpGet("getGalOfNew")]
        public OperResult<GalInfoList> getGalOfNew(string num)
        {
            int curNum;
            if (!int.TryParse(num, out curNum))
            {
                curNum = 10;
            }
            if (curNum > 20)
            {
                curNum = 20;
            }

            using (MyContext context = new())
            {
                var list = context.Gals.OrderByDescending(u => u.ID).Take(curNum).ToList();
                List<GalInfo> ret = new();
                foreach (var item in list)
                {
                    ret.Add(new GalInfo()
                    {
                        Name = item.Name,
                        NickName = item.NickName,
                        NewIndex = item.NewIndex,
                        IsCN = item.IsCN,
                    });
                }
                return OperResult<GalInfoList>.Succeed(new GalInfoList()
                {
                    GalInfos = ret,
                    Count = ret.Count,
                    MaxCount = list.Count,
                });
            }

        }

        #endregion


        #region Admin
        [HttpPost("addFileOfGal")]
        public OperResult<int> addFileOfGal(int userId, string name, string path, string fileId)
        {
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(path) || string.IsNullOrEmpty(fileId))
            {
                return OperResult<int>.Failed("必要项为空!");
            }

            using (MyContext context = new())
            {
                if (!UserTool.GetUserIsOK(context, userId))
                {
                    return OperResult<int>.Failed("当前用户没有权限!");
                }

                var gal = context.Gals.FirstOrDefault(u => u.ID == Convert.ToInt32(fileId));
                if (gal == null)
                {
                    return OperResult<int>.Failed("找不到当前Gal索引!");
                }

                context.FilePaths.Add(new FilePath_Table()
                {
                    FileType = (int)FileTypeEnum.Gal,
                    FileId = Convert.ToInt32(fileId),
                    Name = name,
                    Path = path,
                    UserId = userId,
                    CreateTime = DateTime.Now,
                    DelTime = new DateTime(2001, 06, 04),
                    IsDel = 0
                });
                context.AdminLogs.Add(AdminLog_Table.CreateLog(LogStateEnum.AddFileOfGal, userId, fileId));
                var ret = context.SaveChanges();
                return OperResult<int>.Succeed(ret);
            }
        }

        [HttpPost("addGal")]
        public OperResult<int> addGal(int userId, string name, string nickName, string club, string nickClub, string newIndex, string isCh, string bug, string url, string isCg)
        {
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(newIndex) || string.IsNullOrEmpty(isCh))
            {
                return OperResult<int>.Failed("必要项为空!");
            }

            using (MyContext context = new())
            {
                if (!UserTool.GetUserIsOK(context, userId))
                {
                    return OperResult<int>.Failed("当前用户没有权限!");
                }
                context.Gals.Add(new Gal_Table()
                {
                    Name = name,
                    NickName = nickName,
                    Club = club,
                    NickClub = nickClub,
                    OldIndex = "",
                    NewIndex = newIndex,
                    RootPath = "",
                    IsCN = Convert.ToInt32(isCh),
                    Bug = bug,
                    Url = url,
                    OldPwd = "",
                    ReleaseDate = "",
                    IsCG = Convert.ToInt32(isCg),
                    BackImage = "",
                    IsDel = 0,
                    UserId = userId,
                    CreateDate = DateTime.Now,
                });
                context.AdminLogs.Add(AdminLog_Table.CreateLog(LogStateEnum.AddGal, userId, newIndex));
                var ret = context.SaveChanges();
                return OperResult<int>.Succeed(ret);
            }
        }

        [HttpDelete("delGal")]
        public OperResult<int> delGal(int id, int userId, string pwd)
        {
            if (pwd != "WANGDONG3")
            {
                return OperResult<int>.Failed("密码错误!");
            }

            using (MyContext content = new())
            {
                if (!UserTool.GetUserIsOK(content, userId))
                {
                    return OperResult<int>.Failed("当前用户没有权限!");
                }
                var gal = content.Gals.FirstOrDefault(u => u.ID == id && u.IsDel == 0);
                if (gal == null)
                {
                    return OperResult<int>.Failed("找不到当前Gal");
                }
                else
                {
                    gal.IsDel = 1;
                    var files = content.FilePaths.Where(u => u.FileId == id && u.FileType == 0).ToList();
                    files.ForEach(u =>
                    {
                        u.IsDel = 1;
                    });
                    content.AdminLogs.Add(AdminLog_Table.CreateLog(LogStateEnum.delGal, userId, id));

                    var ret = content.SaveChanges();
                    return OperResult<int>.Succeed(ret);
                }
            }
        }
        #endregion
    }


}
